package com.pdg.android.common;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public abstract class GameDataBase<T> {
	private static final String KEY_CURRENT_STATE = "current_state";
	private T currentState;
	private Context context;
	public final T getCurrentState(){
		return currentState;
	}
	public final void setCurrentState(T theCurrentState){
		currentState = theCurrentState;
	}
	public final void load(SharedPreferences thePreferences){
		setCurrentState(decodeCurrentState(thePreferences.getString(KEY_CURRENT_STATE,getDefaultCurrentState().toString())));
		onLoad(thePreferences);
	}
	public final void commit(SharedPreferences thePreferences){
		SharedPreferences.Editor theEditor = thePreferences.edit();
		theEditor.putString(KEY_CURRENT_STATE, encodeCurrentState(getCurrentState()));
		onCommit(theEditor);
		theEditor.commit();
	}
	protected abstract void onLoad(SharedPreferences thePreferences);
	protected abstract T getDefaultCurrentState();
	protected abstract T decodeCurrentState(String theValue);
	protected abstract String encodeCurrentState(T theValue);
	protected abstract void onCommit(Editor theEditor);
	public Context getContext() {
		return context;
	}
	public void setContext(Context context) {
		this.context = context;
	}
}
